package main

import (
	"errors"
	"fmt"
	"strings"
)

// 最终产品：云服务器实例
type CloudServer struct {
	CPU     string // 示例：8核Intel Xeon
	Memory  string // 示例：32GB DDR4
	Storage string // 示例：1TB NVMe SSD
	Network string // 示例：10Gbps带宽
}

// 抽象建造者接口
type ServerBuilder interface {
	SetCPU(core int, model string) ServerBuilder
	SetMemory(size int, generation string) ServerBuilder
	SetStorage(diskType string, capacity int) ServerBuilder
	SetNetwork(bandwidth int) ServerBuilder
	Validate() error     // 配置校验
	Build() *CloudServer // 返回最终实例
}

// ---------------------- 具体建造者：标准型服务器 ----------------------
type StandardBuilder struct {
	server CloudServer
}

func (b *StandardBuilder) SetCPU(core int, model string) ServerBuilder {
	// 约束：标准型只能用Intel至强系列
	b.server.CPU = fmt.Sprintf("%d核 %s", core, "Intel Xeon Silver")
	return b
}

func (b *StandardBuilder) SetMemory(size int, generation string) ServerBuilder {
	b.server.Memory = fmt.Sprintf("%dGB DDR4", size)
	return b
}

func (b *StandardBuilder) SetStorage(diskType string, capacity int) ServerBuilder {
	// 约束：标准型必须使用SSD
	if diskType != "SSD" {
		panic("标准型服务器必须使用SSD存储")
	}
	b.server.Storage = fmt.Sprintf("%dTB %s", capacity, diskType)
	return b
}

func (b *StandardBuilder) SetNetwork(bandwidth int) ServerBuilder {
	b.server.Network = fmt.Sprintf("%dGbps带宽", bandwidth)
	return b
}

func (b *StandardBuilder) Validate() error {
	// 示例校验：内存必须≥16GB
	if !strings.Contains(b.server.Memory, "16GB") &&
		!strings.Contains(b.server.Memory, "32GB") &&
		!strings.Contains(b.server.Memory, "64GB") {
		return errors.New("标准型内存最低16GB")
	}
	return nil
}

func (b *StandardBuilder) Build() *CloudServer {
	if err := b.Validate(); err != nil {
		panic("配置校验失败: " + err.Error())
	}
	return &b.server
}

// ---------------------- 指挥者（可选） ----------------------
type Director struct {
	builder ServerBuilder
}

func (d *Director) ConstructBasic() *CloudServer {
	return d.builder.
		SetCPU(4, "Intel").
		SetMemory(16, "DDR4").
		SetStorage("SSD", 500).
		SetNetwork(5).
		Build()
}

func (d *Director) ConstructHighPerformance() *CloudServer {
	return d.builder.
		SetCPU(16, "AMD EPYC").
		SetMemory(64, "DDR4").
		SetStorage("SSD", 2000).
		SetNetwork(40).
		Build()
}

// ---------------------- 客户端调用 ----------------------
func main() {
	builder := &StandardBuilder{}

	// 方式1：客户端直接控制建造过程
	server1 := builder.
		SetCPU(8, "Intel").
		SetMemory(32, "DDR4").
		SetStorage("SSD", 1000).
		SetNetwork(10).
		Build()
	fmt.Printf("自定义服务器: %+v\n", server1)

	// 方式2：通过指挥者复用配置模板
	director := &Director{builder: builder}
	server2 := director.ConstructHighPerformance()
	fmt.Printf("高性能模板: %+v\n", server2)
}
